<?php

namespace app\common\service;

use app\common\model\Goods;

class TimeService
{
    protected $apiId;
    protected $key;
    protected $iv;
    protected $url;

    /**
     * TimeService constructor.
     * @param string $apiId API ID
     * @param string $key 密钥
     * @param string $iv 偏移量
     * @param string $url 请求URL
     */
    public function __construct(string $apiId, string $key, string $iv, string $url)
    {
        $this->apiId = $apiId;
        $this->key = $key;
        $this->iv = $iv;
        $this->url = $url;
    }

    /**
     * 生成签名
     * @param array $params 请求参数数组
     * @param string $key 密钥
     * @return string 签名
     */
    public function generateSignature(array $params, string $key): string
    {
        ksort($params); // 按键名排序
        $data = http_build_query($params) . "&key={$key}"; // 转换成 key=value 格式并添加密钥
        return strtoupper(md5($data)); // 使用MD5加密并转换为大写字符串
    }

    /**
     * 对数据进行加密
     * @param string $data 待加密数据
     * @return string 加密后的数据
     */
    public function encryptData(string $data): string
    {
        $encrypted = openssl_encrypt($data, "AES-128-CBC", $this->key, OPENSSL_RAW_DATA, $this->iv);
        return base64_encode($encrypted); // 返回Base64编码的加密数据
    }

    /**
     * 发送POST请求
     * @param string $url 请求URL
     * @param array $requestData 请求数据
     * @param array $headers 请求头部信息
     * @return array 响应数据
     * @throws \Exception
     */
    public function sendPostRequest(string $url, array $requestData): array
    {
        $curl = curl_init();
        curl_setopt_array($curl, array(
            CURLOPT_URL => $url,
            CURLOPT_RETURNTRANSFER => true,
            CURLOPT_ENCODING => '',
            CURLOPT_MAXREDIRS => 10,
            CURLOPT_TIMEOUT => 0,
            CURLOPT_FOLLOWLOCATION => true,
            CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
            CURLOPT_CUSTOMREQUEST => 'POST',
            CURLOPT_POSTFIELDS => json_encode($requestData),
            CURLOPT_HTTPHEADER => array(
                'User-Agent: Apifox/1.0.0 (https://apifox.com)',
                'Content-Type: application/json'
            ),
        ));
        $response = curl_exec($curl);
        curl_close($curl);
        $data = json_decode($response, true);
        if (isset($data['code']) && $data['code'] == 200) {
            return $data['data'];
        } else {
            throw new \Exception($data['msg']);
        }
    }

    /**
     * 发送请求获取商品列表
     * @param int $page 页数
     * @param int $pageSize 每页获取数量
     * @param string $sort 排序字段
     * @param string $sortType 排序类型
     * @return array 商品列表数据
     * @throws \Exception
     */
    public function fetchGoodsList(int $page = 0, int $pageSize = 20, string $sort = 'add_time', string $sortType = 'desc'): array
    {
        $data = [
            'time' => time(),
            'page' => $page,
            'page_size' => $pageSize,
            'sort' => $sort,
            'sort_type' => $sortType
        ];
        // 构造请求参数
        $requestData = [
            'api_id' => $this->apiId,
            'sign' => $this->generateSignature($data, $this->key),
            'data' => $data
        ];

        // 构造请求URL
        $url = $this->url . '/terminal/api.goods/getGoodsList';

        // 发送POST请求
        return $this->sendPostRequest($url, $requestData);
    }

    /**
     * 发送请求获取商品详情
     * @param int $sku 商品sku编码
     * @param int $library 商品库
     * @return array 商品详情数据
     * @throws \Exception
     */
    public function fetchGoodsInfo(int $sku, int $library): array
    {
        $data = [
            'time' => time(),
            'sku' => $sku,
            'library' => $library,
            //'queryExts' => 'attribute,swiper' // 查询扩展字段，此处指定查询商品属性和轮播图信息
        ];

        // 构造请求参数
        $requestData = [
            'api_id' => $this->apiId,
            'sign' => $this->generateSignature($data, $this->key),
            'data' => $data
        ];

        // 构造请求URL
        $url = $this->url . '/terminal/api.goods/getGoodsInfo';

        // 发送POST请求
        return $this->sendPostRequest($url, $requestData);
    }

    /**
     * 发送请求查询运费
     * @param array $goodsList 商品列表数据
     * @param string $primaryAddress 省市县/区
     * @param string $address 详细地址
     * @return array 运费查询结果
     * @throws Exception
     */
    public function getFreight( $goodsList, string $primaryAddress, string $address): array
    {
        $goodsList = array_values($goodsList);
        $data = [
            'time' => time(),
            'goods_list' => $goodsList,
            'primary_address' => $primaryAddress,
            'address' => $address,
        ];

        // 构造请求参数
        $requestData = [
            'api_id' => $this->apiId,
            'sign' => $this->generateSignature($data, $this->key),
            'data' => $data
        ];

        // 构造请求URL
        $url = $this->url.'/terminal/api.order/getFreight';

        // 发送POST请求
        return $this->sendPostRequest($url, $requestData);
    }

    /**
     * 发送请求查询运费
     * @param array $goodsList 商品列表数据
     * @param string $primaryAddress 省市县/区
     * @param string $address 详细地址
     * @return array 运费查询结果
     * @throws Exception
     */
    public function checkBuy(array $goodsList, string $primaryAddress, string $address): array
    {
        $data = [
            'time' => time(),
            'goods_list' => $goodsList,
            'primary_address' => $primaryAddress,
            'address' => $address,
        ];

        // 构造请求参数
        $requestData = [
            'api_id' => $this->apiId,
            'sign' => $this->generateSignature($data, $this->key),
            'data' => $data
        ];

        // 构造请求URL
        $url = $this->url.'/terminal/api.order/checkBuy';

        // 发送POST请求
        return $this->sendPostRequest($url, $requestData);
    }

    public function placeOrder(array $goodsList, string $primaryAddress, string $address, string $thirdSn, string $consignee, string $mobile, string $remark): array
    {
        $data = [
            'time' => time(),
            'goods_list' => $goodsList,
            'primary_address' => $primaryAddress,
            'address' => $address,
            'third_sn' => $thirdSn,
            'consignee' => $consignee,
            'mobile' => $mobile,
            'remark' => $remark,
        ];

        // 构造请求参数
        $requestData = [
            'api_id' => $this->apiId,
            'sign' => $this->generateSignature($data, $this->key),
            'data' => $data
        ];

        // 构造请求URL
        $url = $this->url.'/terminal/api.order/placeOrder';

        // 发送POST请求
        return $this->sendPostRequest($url, $requestData);
    }



}
